$(document).ready(function() {
    var mouseX;
    var mouseY;
    $(document).mousemove(function(e) {
       mouseX = e.pageX;
       mouseY = e.pageY;
    });
    $('.bar').mouseout(function(){
       $(this).children().fadeOut('slow');
    });

    $('.search').click(function() {
     showView();
     displayLoading();
     closeBox();
   });

   $('input[id=query]').change(function(){
       var topPos = $('.form .select2-container').height()+335;
       $('#results').css('top',topPos);
       var resHeight = $('#results').height()
       $('body').css('min-height', Math.max(920, topPos+resHeight+60))
    });

   $('.celllineBox input').click(function() {
       if(! $(this).is(':checked')){
           if( $(this).attr('id') == $('#refLine').attr('value')){
               $('.cellline .reference').parent('.line').css('background-color', '');
               $('.cellline .reference').removeClass('reference')
                              .addClass('nonreference')
               $('.cellline .refavg')
                          .addClass('reference')
                          .removeClass('nonreference');
               $('.cellline .refavg').parent('.line').css('background-color', '#C6DFFF');
               $('#refLine').attr('value','avg');
           }
       }
       checkNrOfCelllines();
   });

    $(document).keyup(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code === 27) {closeBox();}
    });

    $('.cellline .nonreference').click(function() {
       var $sel = ($(this).attr('id')).replace(' ', '_');
       if($('.cellline input[id='+$sel+']').is(':checked')||($sel=='avg')){
           $('.cellline .reference').parent('.line').css('background-color', '');
           $('.cellline .reference').removeClass('reference')
                          .addClass('nonreference');
           $('.cellline .ref'+$sel.toLowerCase()).parent('.line').css('background-color', '#C6DFFF');
           $('.cellline .ref'+$sel.toLowerCase())
                      .addClass('reference')
                      .removeClass('nonreference');
           $('#refLine').attr('value',$sel);
       }
    });

    $('#type').select2({
        minimumResultsForSearch: 10
    });
    $('#organism').select2({
        minimumResultsForSearch: 10
    });

    $('#query').select2({
        placeholder: "All Proteins",
        tokenSeparators: [";", " "],
        minimumInputLength: 3,
        ajax: {
            url: "/NCI60/Query/suggest",
            dataType: 'jsonp',
            quietMillis: 100,
            data: function (term, page) { // page is the one-based page number tracked by Select2
                return {
                    query: term, //search term
                    max: 10, // page size
                    offset: page // page number
                };
            },
            results: function (data, page) {
                var more = (page * 10) < data.total; // whether or not there are more results available

                // notice we return the value of more so Select2 knows if more results can be loaded
                return {results: data.elements, more: more};
            }
        },
        formatResult: queryFormatResult, // omitted for brevity, see the source of this page
        formatSelection: queryFormatSelection, // omitted for brevity, see the source of this page
        dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
        tags: ['']
        });
        $('.select2-default').css('width', '120px');
    selectLine();
 });
 
 var nextNotClicked = true;

function checkNrOfCelllines(){
    var nrOfChecked = $('.cellline input:checked').size();
    var isActive = true;
    if(nrOfChecked<=1){
        isActive=false;
    }
    activateRegulationButton(isActive);
}

function activateRegulationButton(isActive){
    if(isActive){
        $(".form .search").css("display", "block");
        $(".form .dummy").css("display", "none");
    }else{
        $(".form .search").css("display", "none");
        $(".form .dummy").css("display", "block");
    }
}

function closeBox() {
    $(".expressionPlots").remove();
}

function showView() {
    $(".view").css('display','block');
    $(".search").css('left', 862);
}

function displayLoading() {
    $("#results").html('<div class="loading">Loading...</div>');
}

function selectLine() {
    var $sel = 'BREAST';
    $('.cellline .ref'+$sel.toLowerCase()).parent('.line').css('background-color', '#C6DFFF');
    $('.cellline .ref'+$sel.toLowerCase())
                  .addClass('reference')
                  .removeClass('nonreference');
       $('#refLine').attr('value',$sel);
}

function mouseO(e){
    alert(mouseY+' '+mouseY);
    $('#'+e).css({'top':mouseY,'left':mouseX, 'display':'block'})
            .css('display','block');
}

function queryFormatResult(element) {
        if(element.type=='uniprot'){element.show='Protein Name'}else{element.show=element.type}
        var markup = "<div class='result "+element.type+"'>";
        markup += "<div class='type'>"+element.show+":</div>";
        markup += "<div class='name'>"+element.name+"</div>";
        markup += "<div class='full'>"+element.full+"</div></div>";
        return markup;
    }

function queryFormatSelection(element) {
    return "<div class='"+element.type+"'>"+element.name+"</div>";
}

function setBoxSize(maxHeight){
    var winHeight = $(window).height();
    var maxHeightByWin = winHeight-180;
    var newHeight = Math.max(Math.min(maxHeight,maxHeightByWin),401);
    $(".expressionPlots").height(newHeight);
    $(".expressionPlots .projects").height(newHeight-30);
}

function initResultTable(){
    nextNotClicked = true;
    $('#results .list').scroll(function(){
        if(isScrollBottomReached()&&nextNotClicked){
            $('.loadNext').click();
            $('.loadNext').parent('.listLine').html('<div class="loadNext element">Loading...</div>');
            nextNotClicked = false;
        }
    });
}

function isScrollBottomReached() {
    var divHeight = $('#results .list .data').height()+3;
    var scrollPosition = $('#results .list').height() + $('#results .list').scrollTop();
    return (divHeight == scrollPosition);
}

function getTop(ele)
{
    var eTop = ele.offset().top;
    var wTop = $(window).scrollTop();
    var top = eTop - wTop;

    return top; 
}